import { Component, OnInit, Input } from "@angular/core";
import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { AlertController, ModalController } from "@ionic/angular";
import { HttpService } from "src/app/shared/service/http.service";
import { ActionSheetService } from "ng-zorro-antd-mobile";
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ShowPhoneModalComponent } from '../show-phone-modal/show-phone-modal.component';
@Component({
  selector: "app-button-heap",
  templateUrl: "./button-heap.component.html",
  styleUrls: ["./button-heap.component.scss"]
})
export class ButtonHeapComponent implements OnInit {
  @Input() tagData: any;

  heapLen = 0;
  messageLinkLen = 0;
  constructor(
    private appGlobalService: AppGlobalService,
    private alertController: AlertController,
    private http: HttpService,
    private httpService: HttpService,
    public modalController: ModalController
  ) { }

  ngOnInit() {

    this.heapLen = this.tagData.data.heap ? this.tagData.data.heap.length : 0;
    this.messageLinkLen = this.tagData.data.messageLink ? this.tagData.data.messageLink.length : 0;

  }
  showActionSheet = (item) => {
    const buttons = item.formData.map(
      obj => obj.label
    );
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons
      },
      buttonIndex => {
        console.log(buttonIndex);
        if (buttonIndex >= 0) {
          this.go(
            item.formData[buttonIndex]
          );
        }
      }
    );
  }

  /**
   * 跳转备注页面
   *
   *
   */
  go(item) {
    if (item.link && item.link.type === "url") {

      this.appGlobalService.openUrl('', item.link.url);
    } else if (item.link && item.link.type === "page") {
      // page
      this.appGlobalService.openPage(item.link);
    } else if (item.submit) {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/submit", params, async res => {
        if (res.success === true) {
          this.appGlobalService.showToast(res.message, 2000, 'middle');
          await this.http.reloadCurrentPage();
          // await localStorage.setItem("needRefresh", "true");
        } else {
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      });
    }
  }
  /**
   * 处理点击
   *
   * @param item 参数
   */
  async handleClick(item) {
    if (item.action === "link") {

      if (item.link && item.link.type === 'page') {
        const sessionId = localStorage.getItem("sessionId");
        const pageParams = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId
        };
        this.appGlobalService.goToForward(pageParams);
      } else if (item.link && item.link.type === "ljcontract") {
        const targetObj = { pageId: item.link.target, params: item.link.params, sessionId: localStorage.getItem('sessionId') };
        this.httpService.post('element/ljserviceContract/url', targetObj.params, res => {
          const title = item.text ? item.text : this.tagData.data.label;
          this.appGlobalService.openUrl(title, res.url, item.link.target, JSON.stringify(item.link.params));
        });
      } else if (item.link && item.link.type === 'modal') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpData = JSON.parse(res.script).views[0].tags[0].data;
          this.showRecommenMessage(tmpData);
        });
      }
    } else if (item.action === "question") {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      const alert = await this.alertController.create({
        header: item.question,
        buttons: [
          {
            text: "取消",
            role: "cancel"
          },
          {
            text: "确定",
            handler: () => {
              this.http.post("application/submit", params, async res => {
                if (res.success === true) {
                  this.appGlobalService.showToast(res.message, 2000, 'middle');
                  await this.http.reloadCurrentPage();
                  // await localStorage.setItem("needRefresh", "true");
                } else {
                  this.appGlobalService.showToast(res.message, 2000, 'middle');
                }
              });
            }
          }
        ]
      });
      await alert.present();
    } else if (item.modelType === "iconLink") {
      this.remarkList(item);
    } else if (item.action === 'submitLink') {
      if (this.tagData.data.heap) {
        let linkSubmit;
        for (let index = 0; index < this.heapLen; index++) {
          const element = this.tagData.data.heap[index];
          if (element.submit && element.submit.content && element.submit.content.submitType) {
            linkSubmit = element.submit;
            break;
          }
        }
        const params = {
          content: linkSubmit.content,
          id: linkSubmit.id,
          sessionId: localStorage.getItem('sessionId')
        };
        // 请求获取新数据
        this.httpService.post('application/submit', params, res => {
          // 请求数据成功
          if (res.success) {
            if (res.params.eventReturnParam) {
              item.link.params[res.params.eventReturnParam] = res.params[res.params.eventReturnParam];
            }
            this.appGlobalService.openPage(item.link);
          } else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, 'middle');
          });
      }
    }
  }


  remarkList(more) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    } else if (more.links) {
      more.listRemark = more.links;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );
  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.action === 'link') {
      // 修改 领取类型按钮
      const params = {
        pageId: itemObj.link.target,
        params: itemObj.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
    }
  }





  // 推荐语
  async showRecommenMessage(tagData) {
    // 是否公开号码
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'show-phone-modal',
      component: ShowPhoneModalComponent,
      componentProps: { tagData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

}
